package com.feige.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feige.helper.PermissionHelper;
import com.feige.pojo.Permission;
import com.feige.dao.PermissionMapper;
import com.feige.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feige.service.RolePermissionService;
import com.feige.utils.common.Admin;
import com.feige.utils.jwt.JwtInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 权限管理 服务实现类
 * </p>
 *
 * @author feige
 * @since 2020-07-20
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    RolePermissionService rolePermissionService;

    /**
     * 获取对应用户的权限值
     * @param userId
     * @return
     */
    @Override
    public Set<String> selectPermissionValueByUserId(Long userId) {
        return baseMapper.selectPermissionValueByUserId(userId);
    }

    /**
     * 管理员有所有权限
     * @return
     */
    @Override
    public Set<String> selectAllPermissionValue() {
        return baseMapper.selectAllPermissionValue();
    }

    /**
     * 根据角色ID查对应的权限
     * @param roleId
     * @return
     */
    @Override
    public List<Permission> selectPermissionByRoleId(Long roleId) {
        List<Long> permissionId = rolePermissionService.getPermissionId(roleId);
        return baseMapper.selectBatchIds(permissionId);
    }

    @Override
    public List<Permission> selectPermissionByUserId(JwtInfo jwtInfo) {
        List<Permission> permissionList;
        if (Admin.isAdmin(jwtInfo.getNum())){
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("type",1).or().eq("type",2);
            permissionList = this.baseMapper.selectList(wrapper);

        }else {
            permissionList = this.baseMapper.selectPermissionByUserId(jwtInfo.getId());
        }
        return PermissionHelper.build(permissionList);
    }

    @Override
    public List<Permission> queryAllMenu() {
        List<Permission> permissions = baseMapper.selectList(null);
        return PermissionHelper.build(permissions);
    }

}
